package com.geh.learn.util;

import com.geh.learn.bean.Student;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Comparator 比接口 Comparatable要简易
 * <p>
 * Created by gehui on 2017/2/23.
 */
public class ArrayListLearn {
    public static void main(final String[] args) {
        final List<Integer> listInitTest = new ArrayList<Integer>() {
            {
                add(1);
                for (int i = 2; i <= 10; i++) {
                    add(i);
                }
            }
        };

        List<Student> slist = new ArrayList<Student>() {
            {
                add(new Student("001", "Mike", 82));
                add(new Student("002", "Joe", 73));
                add(new Student("003", "Lily", 99));
            }
        };

        // 传统写法
        Collections.sort(slist, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                if (s1.getScore() > s2.getScore()) {
                    return 1;
                } else if (s1.getScore() == s2.getScore()) {
                    return 0;
                } else {
                    return -1;
                }
            }
        });

        // 普通lambda表达式
        Comparator<Student> c = (Student s1, Student s2) -> {
            if (s1.getScore() > s2.getScore()) {
                return 1;
            } else if (s1.getScore() == s2.getScore()) {
                return 0;
            } else {
                return -1;
            }
        };
        Collections.sort(slist, c);

        // 第一种lambda表达式
        Comparator<Student> byScore1 = Comparator.comparing(s -> s.getScore());
        Collections.sort(slist, byScore1);

        // 第二种lambda表达式
        Comparator<Student> byScore2 = Comparator.comparing(Student::getName);
        Collections.sort(slist, byScore2);

        // 综合成一个
        Collections.sort(slist,
                (Student s1, Student s2) -> {
                    if (s1.getScore() > s2.getScore()) {
                        return 1;
                    } else if (s1.getScore() == s2.getScore()) {
                        return 0;
                    } else {
                        return -1;
                    }
                });

        // 比较对象有Compare的情况下
        Collections.sort(slist, (Student s1, Student s2) -> s1.getName().compareTo(s2.getName()));

        // 更加简化的写法
        slist.sort((Student s1, Student s2) -> s1.getName().compareTo(s2.getName()));

        // 或者
        slist.sort(Comparator.comparing(Student::getScore));

    }
}
